package utils

import (
	"camera_app/entity"
	"fmt"
	"log"

	"github.com/golang-jwt/jwt/v5"
)

var KEY = []byte("xwyzsn_0117")

func GenerateToken(user entity.User) (string, error) {
	t := jwt.NewWithClaims(jwt.SigningMethodHS256,
		jwt.MapClaims{
			"iss":      "auth-server",
			"sub":      "",
			"username": user.Username,
			"password": user.Password,
			"userId":   user.UserId,
		},
	)
	fmt.Println(user)
	s, err := t.SignedString(KEY)
	if err != nil {
		log.Fatal("JWT generate Error ", err.Error())
	}
	return s, err
}

func ParseToken(tokenString string) (interface{}, error) {
	t, err := jwt.NewParser().Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
		return KEY, nil
	})
	if err != nil {
		return nil, err
	}
	if !t.Valid {
		return nil, fmt.Errorf("invalid token")
	}
	return t.Claims, nil
}
